package com.zhang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.entity.Menu;
import com.zhang.entity.Role;
import com.zhang.entity.RoleMenu;
import com.zhang.mapper.MenuMapper;
import com.zhang.mapper.RoleMenuMapper;
import com.zhang.service.MenuService;
import com.zhang.utils.MenuTreeBuild;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author Zhang
 * @since 2022-03-02
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private  MenuMapper menuMapper;
    /**
     * 功能描述: <br>
     * 〈获取菜单树〉
     *
     * @Param: [menuList]
     * @Return: java.util.List<com.zhang.entity.Menu>
     * @Author: Mr.zhang
     * @Date: 2022/3/3 10:01
     */
    @Override
    public List<Menu> findMenuTree() {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        //查询可用的菜单
        queryWrapper.eq("type", 0);
        List<Menu> menuTree = MenuTreeBuild.build(this.baseMapper.selectList(queryWrapper));
        return menuTree;
    }

    /**
     * 根据用户的角色查询菜单
     * @param roles
     * @return
     */
    @Override
    public List<Menu> findMenuByRoles(List<Role> roles) {
        List<Menu> menus=new ArrayList<>();
        if(!CollectionUtils.isEmpty(roles)){
            Set<Long> menuIds=new HashSet<>();//存放用户的菜单id
            List<RoleMenu> roleMenus;
            for (Role role : roles) {
                //根据角色id获取userrole中间表的菜单id
                roleMenus= roleMenuMapper.selectByReloId(role.getId());
                if(!CollectionUtils.isEmpty(roleMenus)){
                    for (RoleMenu roleMenu : roleMenus) {
                        menuIds.add(roleMenu.getMenuId());
                    }
                }
            }
            if(!CollectionUtils.isEmpty(menuIds)){
                for (Long menuId : menuIds) {
                    //该用户所有的菜单
                    Menu menu = menuMapper.selectByPrimaryKey(menuId);
                    if(menu!=null){
                        menus.add(menu);
                    }
                }
            }
        }
        return menus;
    }
}

